/* eslint-disable no-useless-constructor */
/* eslint-disable no-empty */
import React, { Suspense, lazy } from "react";
import {
  BrowserRouter as Router,
  Redirect,
  Route, Switch
} from "react-router-dom";
import { Provider as MobxProvider } from 'mobx-react'
import { createBrowserHistory } from 'history';
import routes from "../config/routes.config.js"
import Cookies from 'js-cookie'
import Store from '@/store/index'
import Header from '../components/Header/index.tsx'
import { message } from "antd"
import PreLoading from '@/components/PreLoadingPage/index.tsx'
import nprogress from 'nprogress'
import 'nprogress/nprogress.css'
const NotFound = lazy(() => import('@/views/404/index.tsx'))

// const history = createBrowserHistory() // history模式
const history = createBrowserHistory() // hash模式
function RouteWithSubRoutes(route) {
  React.useState(nprogress.start());
  React.useEffect(() => {
    nprogress.done();
    return () => nprogress.start();
  });
  return (
    <Route
      exact
      path={route.path}
      render={props => {
        document.title = route.title || "个人博客"
        console.log(route.path, '路由是')

        if (route.isLogin && !Store.loginStatus) {
          message.error('请先登录')
          return <Redirect to='/login' /> // 一个简单的路由拦截
        }
        if (route.requireHeader) { // 判断是否需要公共头部组件
          return (
            <>
              <Header />
              <route.component {...props} routes={route.routes} />
            </>
          )
        } else {
          return (
            <route.component {...props} routes={route.routes} />
          )
        }
      }
      }
    />

  );
}

class App extends React.Component {
  constructor(props) {
    super(props)
  }
  componentWillMount() {
    if (Cookies.get('userInfo')) {
      Store.setUserInfo(JSON.parse(Cookies.get('userInfo')))
      console.log(Cookies.get('userInfo'))
    }
  }
  render() {
    return (
      <MobxProvider>
        <Router history={history} >
          {/* <Redirect from='/' to='/index' /> */}
          {/* // 使用路由懒加载 */}
          <Suspense fallback={<PreLoading />}>
            <Switch>
              {routes.map((route, i) => {
                return <RouteWithSubRoutes key={i} {...route} />
              }
              )}
              <Route component={NotFound} />
            </Switch>
          </Suspense>
        </Router>
      </MobxProvider>
    )
  }
}
export default App
